package br.edu.ufcg.lsd.wbis.control.util.matching;

/**
 * @author Renato Miceli
 */
public class StringMatcher extends AbstractMatcher {

	public static enum StringMatchingType {

		DEFAULT, CONTAINS, STARTS_WITH, ENDS_WITH;

	}

	private final Boolean caseSensitive;

	private final StringMatchingType matchingType;

	public StringMatcher(Boolean caseSensitive, StringMatchingType matchingType) {
		this.caseSensitive = caseSensitive;
		this.matchingType = matchingType;
	}

	public Boolean getCaseSensitive() {
		return caseSensitive;
	}

	public StringMatchingType getMatchingType() {
		return matchingType;
	}

	public boolean matches(String value, String comparableValue) {
		if (!isMatcheable(value) || !isMatcheable(comparableValue) || !isMatcheable(this.matchingType)) {
			return true;
		}

		if (!this.caseSensitive) {
			value = value.toLowerCase();
			comparableValue = comparableValue.toLowerCase();
		}

		switch (this.matchingType) {
		case DEFAULT:
			if (!comparableValue.equals(value)) {
				return false;
			}
			break;
		case CONTAINS:
			if (!comparableValue.contains(value)) {
				return false;
			}
			break;
		case STARTS_WITH:
			if (!comparableValue.startsWith(value)) {
				return false;
			}
			break;
		case ENDS_WITH:
			if (!comparableValue.endsWith(value)) {
				return false;
			}
			break;
		}

		return true;
	}
	
	protected boolean isMatcheable(Object value) {
		return super.isMatcheable(value) && !value.toString().equals("");
	}
	
	@Override
	public String toString() {
		return matchingType + " . Case sensitive: " + caseSensitive;
	}

}
